#include "JSerialize.h" 


JCharPtr JSerialize::SerializeString(std::string data,int& selfLength)
{
	//int size = data.length();
	//char* c = new char[sizeof(int)+size];
	//memcpy(c,&size,sizeof(int));
	//memcpy(c + sizeof(int),data.c_str(),size);
	//selfLength = sizeof(int) + size;
	//return JCharPtr(c);
	int size = data.length();
	char* c = new char[sizeof(int)+size];
	JCharPtr ptr(c);
	memcpy(&(*ptr),&size,sizeof(int));
	memcpy(&(*ptr) + sizeof(int),data.c_str(),size);
	selfLength = sizeof(int) + size;
	return ptr;
}

JCharPtr JSerialize::SerializeIntArray(int*& intArray,int size,int& selfLength)
{
	selfLength = (size + 1)*sizeof(int);
	char* c = new char[selfLength];
	memcpy(c,&size,sizeof(int));
	memcpy(c+sizeof(int),intArray,size*sizeof(int));
	return JCharPtr(c);
}

JCharPtr JSerialize::SerializeVectorInt(std::vector<int> vec,int& selfLength)
{
	int size = vec.size()*sizeof(int);
	selfLength = size+sizeof(int);
	char* c = new char[selfLength];
	memcpy(c,&size,sizeof(int));
	for(int i = 0;i < vec.size(); ++i)
	{
		memcpy(c+(i+1)*sizeof(int),&(vec[i]),sizeof(int));
	}

	return JCharPtr(c);
}

JCharPtr JSerialize::SerializeClassHead(std::string className,int classSize,int& selfLength)
{
	selfLength = classNameLength+sizeof(int);
	char* head = new char[selfLength];
	memset(head,0,classNameLength+sizeof(int));
	memcpy(head,className.c_str(),classNameLength);
	memcpy(head+classNameLength,&classSize,sizeof(int));
	return JCharPtr(head);
}

JCharPtr JSerialize::SerializeInt(int data,int& selfLength)
{
	char* tmp = new char[sizeof(int)];
	memcpy(tmp,&data,sizeof(int));
	selfLength = sizeof(int);
	return JCharPtr(tmp);
}

void JSerialize::ReSerializeClassHead(JCharPtr data,std::string& className,int& classSize,int& selfSize)
{
	char tmp[classNameLength];
	memcpy(tmp,data.get(),classNameLength);
	className.assign(tmp);
	memcpy(&classSize,data.get()+classNameLength,sizeof(int));
	selfSize = classNameLength + sizeof(int);
}

void JSerialize::ReSerializeIntArray(JCharPtr data,std::vector<int>& vecArray,int& selfSize)
{
	int arraySize;
	memcpy(&arraySize,data.get(),sizeof(int));
	selfSize = sizeof(int);
	for(int i = 0;i < arraySize; ++i)
	{
		int tmp;
		memcpy(&tmp,data.get()+sizeof(int)*(1+i),sizeof(int));
		vecArray.push_back(tmp);
		selfSize += sizeof(int);
	}
}

void JSerialize::ReSerializeString(JCharPtr data,std::string& s,int& selfSize)
{
	int size;
	memcpy(&size,data.get(),sizeof(int));
	char* tmp = new char[size+1];
	memset(tmp,'\0',size+1);
	memcpy(tmp,data.get()+sizeof(int),size);
	s.assign(tmp);
	selfSize = sizeof(int) + size;
}

